<template>
    <div class="subject">
        <div v-for="(item, index) in list" :key="index">
            <span>{{ item.math1 }}</span>
            <span>+</span>
            <span>{{ item.math2 }}</span>
            <span>=</span>
            <input type="number" :value="item.sum" @input="handleInput(index, $event)" />
            <button @click="finish(index)">提交</button>
        </div>

    </div>
</template>

<script>
import Bus from '@/utils/BusEvent';
export default {

    created() {
        let maths = JSON.parse(localStorage.getItem('mathList'))
        if (maths.length) {
            this.list = maths
        } else {
            for (let i = 0; i < 5; i++) {
                let firstData = ~~(Math.random() * 50)
                let lastData = ~~(Math.random() * 50)
                this.list.push({
                    math1: firstData,
                    math2: lastData,
                    sum: ''
                })
            }
        }

    },
    watch: {
        list: {
            deep: true,
            immediate: true,
            handler() {
                Bus.$emit('list', this.list)
            }
        }
    },
    data() {
        return {
            list: [],
            tempValue: '',
            change:false
        }
    },
    methods: {
        finish(i) {
            if (i !== null) {
                if (!this.tempValue) {
                    return alert('请输入答案')
                }
                this.list[i].sum = this.tempValue
            }
            localStorage.setItem('mathList', JSON.stringify(this.list))
            Bus.$emit('list', this.list)
        },
        handleInput(i, event) {
            this.change = true
            console.log(`输入框 ${i} 的值为：${event.target.value}`);
            this.tempValue = event.target.value
        }
    }

}
</script>

<style scoped>
.subject {
    margin: 5px;
    padding: 5px;
    font-size: 20px;
}

.subject span {
    display: inline-block;
    text-align: center;
    width: 20px;
}

.subject input {
    width: 50px;
    height: 20px;
}
</style>